# views.py: 路由，视图函数
# 蓝图
import datetime

from flask import Blueprint, render_template, request, redirect,session
from .models import *
blue = Blueprint('user',__name__)
# blue2 = Blueprint('product',__name__)
@blue.route('/')
@blue.route('/home/')
def home():
    #  4. 获取cookie
    # username = request.cookies.get('user')
    # 获取session
    username = session.get('user')
    return render_template('home.html',user_name=username)

@blue.route('/login/',methods=['POST','GET'])
def login_page():
    # GET:访问登录页面
    if request.method == 'GET':
        return render_template('login.html')
    #POST:实现登录功能
    elif request.method == 'POST':
        pass
        # 1. 获取前端提交的数据
        username = request.form.get('username')
        password = request.form.get('password')
        # 2. 模拟登录：用户名和密码验证
        if username == 'aaa' and password == '1234':
            # 登录成功
            response = redirect('/home/')
            # 3. 设置cookie:cookie中不能用中文
            # response.set_cookie('user',username) 默认浏览器关闭cookie失效
            # 过期时间：
            #   max_age；单位是秒，设置经过多少秒后cookie失效
            # response.set_cookie('user',username,max_age=3600*24*7)
            # response.set_cookie('user',username,expires=datetime.datetime(2025,12,12))

            # 设置session
            session['user']=username
            session.permanent = True
            return response
        else:
            return '用户名或密码错误'


# 注销
@blue.route('/logout/')
def logout():
    response = redirect('/home/')
    # 5. 删除cookie
    # response.delete_cookie('user')
    # 删除session
    session.pop('user')
    return response


